/**
 * Copyright 2014 Zhenguo Jin (jinzhenguo1990@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.staginfo.segs.util;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * SDcard操作工具类
 *
 * @author jingle1267@163.com
 */
public final class SDCardUtils {
    private static final String TAG = "SDCardUtils";

    /**
     * Don't let anyone instantiate this class.
     */
    private SDCardUtils() {
        throw new Error("Do not need instantiate!");
    }

    /**
     * Check the SD card
     *
     * @return 是否存在SDCard
     */
    public static boolean checkSDCardAvailable() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * Check if the file is exists
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     * @return 是否存在文件
     */
    public static boolean isFileExistsInSDCard(String filePath, String fileName) {
        boolean flag = false;
        if (checkSDCardAvailable()) {
            File file = new File(filePath, fileName);
            if (file.exists()) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * Write file to SD card
     *
     * @param filePath 文件路径
     * @param filename 文件名
     * @param content  内容
     * @return 是否保存成功
     * @throws Exception
     */
    public static boolean saveFileToSDCard(String filePath, String filename,
                                           String content) throws Exception {
        boolean flag = false;
        if (checkSDCardAvailable()) {
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            File file = new File(filePath, filename);
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(content.getBytes());
            outStream.close();
            flag = true;
        }
        return flag;
    }

    /**
     * Read file as stream from SD card
     *
     * @param fileName String PATH =
     *                 Environment.getExternalStorageDirectory().getAbsolutePath() +
     *                 "/dirName";
     * @return Byte数组
     */
    public static byte[] readFileFromSDCard(String filePath, String fileName) {
        byte[] buffer = null;
        try {
            if (checkSDCardAvailable()) {
                String filePaht = filePath + "/" + fileName;
                FileInputStream fin = new FileInputStream(filePaht);
                int length = fin.available();
                buffer = new byte[length];
                fin.read(buffer);
                fin.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * Delete file
     *
     * @param filePath 文件路径
     * @param fileName filePath =
     *                 android.os.Environment.getExternalStorageDirectory().getPath()
     * @return 是否删除成功
     */
    public static boolean deleteSDFile(String filePath, String fileName) {
        File file = new File(filePath + "/" + fileName);
        if (!file.exists() || file.isDirectory())
            return false;
        return file.delete();
    }


    /**
     * 获取绝对路径
     * @param path 文件相对SD卡或者应用目录的路径
     * @return 绝对路径
     */
    public static String getAbsolutePath(String path) {
        if (checkSDCardAvailable()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + path;
        } else {
            return Environment.getDataDirectory().getAbsolutePath() + "/" + path;
        }
    }

    /**
     * 保存对象到文件中
     * @param filePath
     * @param fileName
     * @param object
     * @return
     */
    public static boolean saveObjectToFile(String filePath, String fileName, Object object) {

        File file = new File(getAbsolutePath(filePath));
        if(!file.exists()){
            file.mkdirs();
        }

        FileOutputStream fos;
        try {
            fos = new FileOutputStream(getAbsolutePath(filePath + fileName));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.flush();
            oos.close();
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtils.d(TAG, e.toString());
            return false;
        }
        return true;
    }

    public static <T extends Object> boolean saveObjectToFile2(String filePath, String fileName, T t) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(getAbsolutePath(filePath + fileName));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(t);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtils.d(TAG, e.toString());
            return false;
        }
        return true;
    }

    public static <T extends Object> T readObjectFromFile2(String filePath, String fileName) {
        T object = null;
        ObjectInputStream ois = null;
        try {
            FileInputStream fis = new FileInputStream(getAbsolutePath(filePath + fileName));
            ois = new ObjectInputStream(fis);
            object = (T) ois.readObject();
        } catch (Exception e) {
            // TODO: handle exception
            LogUtils.d(TAG, e.toString());
            return null;
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    // e.printStackTrace();
                    LogUtils.d(TAG, e.toString());
                }
            } else {
                return null;
            }
        }
        return object;
    }

    /**
     * 删除对象
     * @param filePath
     * @param fileName
     * @return
     */
    public static boolean deleteObjectFromFile(String filePath, String fileName) {
        File file = new File(getAbsolutePath(filePath + fileName));
        if (file.exists()) {
            return file.delete();
        }
        return true;
    }

    /**
     * 从文件中读取对象
     * @param filePath
     * @param fileName
     * @return
     */
    public static Object readObjectFromFile(String filePath, String fileName) {
        Object object = null;
        ObjectInputStream ois = null;
        try {
            FileInputStream fis = new FileInputStream(getAbsolutePath(filePath + fileName));
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
        } catch (Exception e) {
            Logs.d(TAG, e.toString());
            return null;
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    Logs.d(TAG, e.toString());
                }
            } else {
                return null;
            }
        }
        return object;
    }
}
